import logging
import signal
import sys
import time

import config
from minio_handler import minio_client
from tools import logger
from wechat.wechat_channel import WechatChannel


def sigterm_handler_wrap(_signo):
    old_handler = signal.getsignal(_signo)

    def func(_signo, _stack_frame):
        logging.info("signal {} received, exiting...".format(_signo))
        # conf().save_user_datas()
        if callable(old_handler):  # check old_handler
            return old_handler(_signo, _stack_frame)
        sys.exit(0)

    signal.signal(_signo, func)


def run():
    try:
        # init bucket
        if not minio_client.bucket_exists(config.MINIO_BUCKET_NAME):
            minio_client.make_bucket(config.MINIO_BUCKET_NAME)
            logger.info("[INIT] bucket {} created".format(config.MINIO_BUCKET_NAME))
        # wechat_log_config(config.LOG_DIR)
        # Ctrl + C to close
        sigterm_handler_wrap(signal.SIGINT)
        # kill signal
        sigterm_handler_wrap(signal.SIGTERM)
        channel = WechatChannel()
        channel.startup()
        while True:
            time.sleep(1)

    except Exception as e:
        logging.error("Wechat APP start failed!")
        logging.exception(e)


if __name__ == "__main__":
    run()
